<style>
    .dn {
        display: none;
    }

    .attachments {
        display: block;
        float: left;
        overflow: hidden;
        text-align: center;
    }

    .option-item {
        overflow: hidden;
        margin-top: 5px;
        color: #1E9FFF;
        text-align: center;
    }

    .preview {
        cursor: pointer;
    }

    .file-a {
        font-size: 12px;
        word-break: break-all;
        text-overflow: ellipsis;
        overflow: hidden;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        margin-top: 5px;
    }

    .cardU {
        background-image: url(../../assets/images/card_u.png);
        background-repeat: no-repeat;
        background-position: center;
        width: calc(100% - 152px);
        height: 150px;
        padding: 0;
    }

    .cardU img {
        width: 100%;
        height: 100%;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">名称：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="name" class="layui-input" type="text" placeholder="请输入名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">编码：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="code" class="layui-input" type="text" placeholder="请输入编码"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">仓库：</label>
                                    <div class="layui-input-inline mr0">
                                        <select name="warehouseId" lay-filter="warehouseId" lay-search lay-verify="">
                                            <option value=""> 请选择仓库</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit>查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="warehouseAreaBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="warehouseAreaTable" lay-filter="warehouseAreaTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="warehouseAreaTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="warehouseAreaForm">
    <form lay-filter="warehouseAreaForm" class="layui-form model-form">
        <input name="id" type="hidden"/>

        <div class="layui-form-item">
            <label class="layui-form-label">仓库类型</label>
            <div class="layui-input-block">
                <select id="warehouseTypeId" name="warehouseTypeId" lay-filter="warehouseTypeId" lay-search lay-verify="required"></select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">仓库</label>
            <div class="layui-input-block">
                <select id="warehouseId" name="warehouseId" lay-filter="getWarehouseInfo" lay-search lay-verify="required">
                    <option value="">请选择仓库</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input"
                       lay-verify="required|isOnlyName" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">编码</label>
            <div class="layui-input-block">
                <input name="code" placeholder="请输入编码" type="text" class="layui-input"
                       lay-verify="required|isOnlySn" required/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">库区图片</label>
            <div class="layui-upload-drag cardU" id="pictureDiv">
                <!--<i class="layui-icon"></i>
                <p>点击上传，或将文件拖拽到此处</p>-->
                <input type="hidden" name="picture" lay-verify="" data-name="仓库图片">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <select name="status">
                    <option value="enable">启用</option>
                    <option value="unable">停用</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">序号</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入序号" type="text" class="layui-input"
                       lay-verify="sortNumber" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注描述</label>
            <div class="layui-input-block">
                <input name="description" placeholder="请输入备注描述" type="text" class="layui-input" lay-verify=""
                       required/>
            </div>
        </div>

        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="warehouseAreaFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>

    var $, config;

    function stopBubbling(e) {
        e = window.event || e;
        if (e.stopPropagation) {
            e.stopPropagation();      //阻止事件 冒泡传播
        } else {
            e.cancelBubble = true;   //ie兼容
        }
    }

    //下载文件
    function downloadFile(realName, url) {
        stopBubbling(this);

        var $downForm = $("<form method='get'></form>");
        $downForm.attr("action", config.base_server + "api-file/downloadFile");
        var $input = $("<input type='hidden'>");
        $input.attr("name", "url");
        $input.val(url);
        $downForm.append($input);
        var $input1 = $("<input type='hidden'>");
        $input1.attr("name", "filename");
        $input1.val(realName);
        $downForm.append($input1);
        var $input2 = $("<input type='hidden'>");
        $input2.attr("name", "access_token");
        $input2.val(config.getToken().access_token);
        $downForm.append($input2);
        $(document.body).append($downForm);
        //提交表单，实现下载
        $downForm.submit();
    }

    //预览
    function previewImg(index) {
        stopBubbling(this);

        var obj = $(index).parent().prev().prev();
        var img = new Image();
        img.src = obj.attr("src");
        var height = img.height; //获取图片高度
        var width = img.width; //获取图片宽度
        if (width > 1000) {
            height = 1000 / width * height;
            width = 1000;
            if (height > 800) {
                width = 800 / height * width;
                height = 800;
            }
        }
        if (height > 800) {
            width = 800 / height * width;
            height = 800;
        }

        var imgHtml = "<img src='" + obj.attr("src") + "' style='width: " + width + "px; height: " + height + "px;' />";
        //弹出层
        layer.open({
            type: 1,
            shade: 0.8,
            offset: 'auto',
            area: [width + 'px', (height + 50) + 'px'],
            shadeClose: true,//点击外围关闭弹窗
            scrollbar: false,//不现实滚动条
            title: "图片预览", //不显示标题
            content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            cancel: function () {
                //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
            }
        });
    }

    layui.use(['layer', 'form', 'table', 'admin', 'laytpl', 'upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laytpl = layui.laytpl;

        // 渲染表格
        var insTb = table.render({
            elem: '#warehouseAreaTable',
            url: config.base + 'enterprisecab/warehouse/admin/warehouseArea/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers'}
                , {field: 'name', align: 'center', title: '名称', width: 180}
                , {field: 'code', align: 'center', title: '编码', width: 180}
                , {field: 'warehouseName', align: 'center', title: '仓库', width: 180}
                , {field: 'warehouseTypeName', align: 'center', title: '仓库类型', width: 180}
                , {field: 'statusDesc', align: 'center', title: '状态'}
                , {field: 'sortNumber', align: 'center', title: '序号'}
                , {field: 'description', align: 'center', title: '备注'}
                , {field: 'createTime', align: 'center', title: '创建时间', width: 180}
                , {align: 'center', toolbar: '#warehouseAreaTableBar', title: '操作', width: 200}
            ]]
        });

        admin.req('enterprisecab/warehouse/admin/warehouse/list', {limit: 9999}, function (res) {
            if (200 == res.code) {
                var optionHtml = '<option value=""> 请选择仓库</option>';
                for (var k = 0; k < res.data.length; k++) {
                    optionHtml += '<option value="' + res.data[k].id + '">' + res.data[k].name + '</option>';
                }
                $("select[name='warehouseId']").html(optionHtml);
                form.render('select');

            } else {
                layer.msg('获取仓库失败', {icon: 2, time: 1000});
            }
        }, 'GET');

        // 工具条点击事件
        table.on('tool(warehouseAreaTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            }
        });

        //监听排序
        table.on('sort(warehouseAreaTable)', function (obj) {
            table.reload('warehouseAreaTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        form.verify({
            isOnlySn: function (value) {
                var isOnly = true;
                var idVal = $("form input[name='id']").val();
                admin.req('enterprisecab/warehouse/admin/warehouseArea/isOnly', {
                    code: value,
                    id: idVal
                }, function (res) {
                    if (res.code == 200) {
                        isOnly = res.data;
                    }
                }, 'GET', false);
                if (!isOnly) {
                    return "仓库库区编码必须唯一"
                }
            },
            isOnlyName: function (value) {
                var isOnly = true;
                var idVal = $("form input[name='id']").val();
                var nameVal = $("form input[name='name']").val();
                admin.req('enterprisecab/warehouse/admin/warehouseArea/isOnly', {
                    name: nameVal,
                    id: idVal
                }, function (res) {
                    if (res.code == 200) {
                        isOnly = res.data;
                    }
                }, 'GET', false);
                if (!isOnly) {
                    return "仓库库区名称必须唯一"
                }
            }
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            let field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#warehouseAreaBtnAdd').click(function () {
            showEditModel();
        });

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '860px',
                offset: '120px',
                title: data ? '修改仓库库区' : '添加仓库库区',
                content: $('#warehouseAreaForm').html(),
                success: function () {
                    //图片上传
                    upload.render({
                        elem: '#pictureDiv'
                        , url: config.upload_url + 'upload?path=' + img_path
                        , auto: true
                        , acceptMime: 'image/*'
                        , headers: {authorization: 'Bearer ' + config.getToken()}
                        , done: function (res) {
                            layer.closeAll('loading');
                            layer.msg('上传成功');
                            var imgUrl = res.data.url;
                            // if(imgUrl){
                            //     imgUrl=imgUrl.substring(imgUrl.indexOf('/')+1)
                            // }
                            //上传完毕回调
                            $("#pictureDiv").html('<img src="' + imgUrl + '" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="picture" value="' + imgUrl + '">');
                        }
                        , error: function (data) {
                            layer.closeAll('loading');
                        }
                    });

                    if (data != undefined) {
                        var picture = data.picture;
                        if (picture) {
                            $("#pictureDiv").html('<img src="' + picture + '" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="picture" value="' + picture + '">');
                        }
                        form.val('warehouseAreaForm', data);
                    }

                    //仓库类型
                    admin.initDataSelect("enterprisecab/warehouse/admin/warehouseType/list", {limit: 9999}, "warehouseTypeId", data ? data.warehouseTypeId : null, "仓库类型", null, null);

                    //仓库列表
                    var selectWarehouseList = function(warehouseType) {
                        admin.req('enterprisecab/warehouse/admin/warehouse/list', {limit: 9999,warehouseTypeId: warehouseType}, function (res) {
                            if (200 == res.code) {
                                var optionHtml = '<option value=""> 请选择仓库</option>';
                                for (var k = 0; k < res.data.length; k++) {
                                    optionHtml += '<option value="' + res.data[k].id + '">' + res.data[k].name + '</option>';
                                }
                                $("select[name='warehouseId']").html(optionHtml);
                                form.render('select');
                                if (data && data.warehouseId != undefined) {
                                    $("select[name='warehouseId']").val(data.warehouseId);
                                    form.render('select');
                                }

                                form.on("select(getWarehouseInfo)", function (data) {
                                    res.data.forEach(item => {
                                        if (item.id === data.value) {
                                            $("form input[name='name']").val(item.name + "-");
                                            $("form input[name='code']").val(item.code + "-");
                                        }
                                    })
                                });
                            } else {
                                layer.msg('获取仓库失败', {icon: 2, time: 1000});
                            }
                        }, 'GET');
                    }


                    //编辑-仓库列表
                    if(data){
                        selectWarehouseList(data.warehouseTypeId);
                    }

                    //仓库类型选择事件
                    form.on("select(warehouseTypeId)", function (data) {
                        selectWarehouseList(data.value);
                    });

                    if (data) {
                        var option = $("form select[name='status']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.status == item.text) {
                                data.status = item.value;
                            }
                        });
                    }

                    if (data) {
                        var option = $("form select[name='warehouseFeatureType']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.warehouseFeatureType == item.text) {
                                data.warehouseFeatureType = item.value;
                            }
                        });
                    }

                    form.val('warehouseAreaForm', data);
                    // 表单提交事件
                    form.on('submit(warehouseAreaFormSubmit)', function (d) {
                        layer.load(2);
                        var url = 'enterprisecab/warehouse/admin/warehouseArea/add'
                        if (data) {
                            url = 'enterprisecab/warehouse/admin/warehouseArea/update';
                        }
                        admin.req(url, d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('warehouseAreaTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprisecab/warehouse/admin/warehouseArea/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 导出excel
        $('#warehouseBtnExport').click(function () {
            var checkRows = table.checkStatus('warehouseAreaTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

    });
</script>